﻿using Enter.Utils;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;

namespace Enter.Dashboard.Api.Filters
{
    // https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-5.0
    // [TypeFilter(typeof(ExceptionFilter))]
    public class ExceptionFilter : IExceptionFilter
    {
        private readonly ILogger<ExceptionFilter> _logger;
        public ExceptionFilter(ILogger<ExceptionFilter> logger)
        {
            _logger = logger;
        }
        public void OnException(ExceptionContext context)
        {
            _logger.LogError(context.Exception, string.Format("OnException:{0}", context.Exception.Message));
            var error = new ResponseData<string>(context.Exception == null ? "请求异常." : context.Exception.Message);
            context.Result = new JsonResult(error);
        }
    }
}
